/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * EdicaoPedido.java
 *
 * Created on 26/10/2013, 09:01:29
 */
package Formularios;

import Classes.EdicaoPedidoClass;
import Classes.ProdutoPSemanaClass;
import DAO.EdicaoPedidoDAO;
import DAO.ProdutoPSemanaDAO;
import Util.HibernateUtil;
import java.awt.Color;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Session;

/**
 *
 * @author Carlos Schaefer
 */
public class EdicaoPedido extends javax.swing.JFrame {

    
    private int semana;
    private int ano;

    public int getAno() {
        return ano;
    }

    public void setAno(int ano) {
        this.ano = ano;
    }

    public int getSemana() {
        return semana;
    }

    public void setSemana(int semana) {
        this.semana = semana;
    }
    
    /** Creates new form EdicaoPedido */
    public EdicaoPedido() {
        initComponents();
        setLocationRelativeTo(null);
        getContentPane().setBackground(Color.WHITE);
       
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        txtsemana = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lblDtInicial = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        lblDtFinal = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtAno = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblprevissao = new javax.swing.JTable();
        jLabel9 = new javax.swing.JLabel();
        btnIncluir = new javax.swing.JButton();
        btnProduto = new javax.swing.JButton();
        btnEditar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        addWindowFocusListener(new java.awt.event.WindowFocusListener() {
            public void windowGainedFocus(java.awt.event.WindowEvent evt) {
                formWindowGainedFocus(evt);
            }
            public void windowLostFocus(java.awt.event.WindowEvent evt) {
            }
        });
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel1.setText("Semana:");

        txtsemana.setFont(new java.awt.Font("Tahoma", 1, 18));
        txtsemana.setText("1");

        jLabel3.setText("Data Inicial");

        lblDtInicial.setText("01/01/2013");

        jLabel5.setText("Data Final");

        lblDtFinal.setText("07/01/2013");

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel7.setText("Ano:");

        txtAno.setFont(new java.awt.Font("Tahoma", 1, 18));
        txtAno.setText("2013");

        tblprevissao.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Códigoregistro", "Cliente", "Código Produto", "Produto", "Data de Conclusão", "Valor do Produto"
            }
        ));
        tblprevissao.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblprevissaoMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tblprevissao);
        tblprevissao.getColumnModel().getColumn(0).setMinWidth(0);
        tblprevissao.getColumnModel().getColumn(0).setPreferredWidth(0);
        tblprevissao.getColumnModel().getColumn(0).setMaxWidth(0);
        tblprevissao.getColumnModel().getColumn(2).setMinWidth(0);
        tblprevissao.getColumnModel().getColumn(2).setPreferredWidth(0);
        tblprevissao.getColumnModel().getColumn(2).setMaxWidth(0);

        jLabel9.setText("Previsão da Semana");

        btnIncluir.setText("Incluir Produto");
        btnIncluir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIncluirActionPerformed(evt);
            }
        });

        btnProduto.setText("Excluir Produto");
        btnProduto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnProdutoActionPerformed(evt);
            }
        });

        btnEditar.setText("Editar Produto");
        btnEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEditarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtsemana)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
                                .addComponent(jLabel7)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(txtAno))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblDtInicial)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(lblDtFinal)))
                        .addGap(189, 189, 189))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel9)
                        .addContainerGap(327, Short.MAX_VALUE))))
            .addGroup(layout.createSequentialGroup()
                .addGap(57, 57, 57)
                .addComponent(btnIncluir)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnEditar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnProduto)
                .addContainerGap(56, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(txtsemana)
                    .addComponent(jLabel7)
                    .addComponent(txtAno))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(lblDtInicial)
                    .addComponent(jLabel5)
                    .addComponent(lblDtFinal))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 19, Short.MAX_VALUE)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 219, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnIncluir)
                    .addComponent(btnProduto)
                    .addComponent(btnEditar)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnIncluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIncluirActionPerformed
         PedidoPrevisaoDialogForm pedidoPrevisaoDaialog = new PedidoPrevisaoDialogForm(this, true);
         pedidoPrevisaoDaialog.setModo(1);
         pedidoPrevisaoDaialog.setVisible(true);        
    }//GEN-LAST:event_btnIncluirActionPerformed

private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
   Listar();
   
   
   preencherGrid();
   
}//GEN-LAST:event_formWindowOpened

private void btnEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditarActionPerformed

    if (produtoPsemana.getcodigo() != 0){
    
        PedidoPrevisaoDialogForm pedidoPrevisaoDaialog = new PedidoPrevisaoDialogForm(this, true);
        pedidoPrevisaoDaialog.setModo(2);
        pedidoPrevisaoDaialog.setProdutoPsemana(produtoPsemana);
        pedidoPrevisaoDaialog.setVisible(true); 
    } else {
        JOptionPane.showMessageDialog(null, "Não há registro selecionado!!\nSelecione um registro!");
    }
    
    
   
   
    
}//GEN-LAST:event_btnEditarActionPerformed

private void tblprevissaoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblprevissaoMouseClicked

    
    int linha = tblprevissao.getSelectedRow();
    int codigo = 0;
     
    codigo = Integer.parseInt(String.valueOf(tblprevissao.getValueAt(linha, 0))); 
    
    produtoPsemana = Pdao.findbyid(codigo); 
    
    
}//GEN-LAST:event_tblprevissaoMouseClicked

private void btnProdutoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnProdutoActionPerformed

    Pdao.delete(produtoPsemana);
    preencherGrid();
    
}//GEN-LAST:event_btnProdutoActionPerformed

private void formWindowGainedFocus(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowGainedFocus
   preencherGrid();
}//GEN-LAST:event_formWindowGainedFocus

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EdicaoPedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EdicaoPedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EdicaoPedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EdicaoPedido.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new EdicaoPedido().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEditar;
    private javax.swing.JButton btnIncluir;
    private javax.swing.JButton btnProduto;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel lblDtFinal;
    private javax.swing.JLabel lblDtInicial;
    private javax.swing.JTable tblprevissao;
    private javax.swing.JLabel txtAno;
    private javax.swing.JLabel txtsemana;
    // End of variables declaration//GEN-END:variables
    public EdicaoPedidoDAO dao = new EdicaoPedidoDAO();
    public ProdutoPSemanaDAO Pdao = new ProdutoPSemanaDAO();
    private ProdutoPSemanaClass produtoPsemana = new ProdutoPSemanaClass();
    
    private void preencherGrid() {
       
        
        DefaultTableModel model  = (DefaultTableModel) tblprevissao.getModel();
        model.setNumRows(0);        
        List Listahh = dao.ProdutoNaSemana(ano, semana);
        DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM  );
        for (int j=0;j<(Listahh.size());j++ ) {
            Object[] obj = (Object[]) Listahh.get(j);
            //Calendar c = Calendar.getInstance();
            //c = (Calendar) obj[4];
            if (obj[1]==null){
                obj[1]="";
            }
            model.addRow(new String[]{
                        "" + obj[0],
                        "" + obj[1],
                        "" + obj[2],
                        "" + obj[3],
                        //"" + obj[4],
                        "" + df.format(obj[4]),
                        "" + obj[5]
                    
                    
                    });
        }
        
    }
    
    
    
    
    private String Data_Inicial(int semana, int ano) {
        
        //Date dt_inicial= new Date();
        
        Calendar c = Calendar.getInstance();
        c.set(ano,00,01);
        c.add(Calendar.WEEK_OF_YEAR,semana );
        c.add(Calendar.DAY_OF_YEAR,-1 );
        DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM  );
        
        return (df.format(c.getTime()));
        
    }
    
    
    private String Data_final(int semana, int ano) {
        
        //Date dt_inicial= new Date();
        
        Calendar c = Calendar.getInstance();
        c.set(ano,00,01);
        c.add(Calendar.WEEK_OF_YEAR,semana+1 );
        c.add(Calendar.DAY_OF_YEAR,-1 );
        DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM  );
        
        return (df.format(c.getTime()));
        
    }

    private void Listar() {
       txtAno.setText(""+ano);
       txtsemana.setText(""+semana);
       lblDtInicial.setText(""+Data_Inicial(semana, ano));
       lblDtFinal.setText(""+Data_final(semana, ano));
    }
       
}
